# -*- coding: utf-8 -*-
# @Time    : 2023/9/20 10:30
# @Author  : Jonny
# @File    : LuckDingtalkMain.py
# @Describe: 钉钉消息提醒入口
from flask import Flask, request
from flask_basicauth import BasicAuth
import os
from logging.handlers import TimedRotatingFileHandler
import logging
import time
import json
from LuckDingtalkService import LuckDingtalkService
from LuckDingtalkConstant import LuckDingtalkConstant

app = Flask(__name__)

# 解决中文乱码问题
try:
    app.json.ensure_ascii = False
except:
    app.ensure_ascii = False

# 获取当前脚本的路径
script_dir = os.path.dirname(os.path.abspath(__file__))  # 项目工程路径/app

# 如果works/logs文件夹不存在则创建
if not os.path.exists(os.path.join(script_dir, 'works/logs')):
    os.makedirs(os.path.join(script_dir, 'works/logs'))

app.config['LOG_FILE'] = os.path.join(script_dir, 'works/logs', LuckDingtalkConstant.LOG_FILE)  # 修改log文件路径到logs文件夹下
app.config['LOG_LEVEL'] = logging.INFO
app.config['LOG_FORMAT'] = '%(asctime)s %(levelname)s: %(message)s'

# 配置全局日志
LOG_FILE = app.config['LOG_FILE']
LOG_LEVEL = app.config['LOG_LEVEL']
LOG_FORMAT = app.config['LOG_FORMAT']

# 设置日志格式
formatter = logging.Formatter(LOG_FORMAT)

# 设置日志处理器，按天生成日志文件
handler = TimedRotatingFileHandler(LOG_FILE, when="midnight", interval=1, backupCount=7)  # 每天生成一个新的日志文件，保留最近7天的日志文件
handler.setFormatter(formatter)  # 设置日志格式
handler.setLevel(LOG_LEVEL)  # 设置日志级别

# 创建并配置logger对象
logger = logging.getLogger()  # 获取root logger对象
logger.setLevel(LOG_LEVEL)  # 设置root logger的日志级别
logger.addHandler(handler)  # 添加handler到root logger对象中
logger.info('Start of the program')  # 输出一条info级别的日志，用于测试日志功能是否正常开启

global config

# 从环境变量中读取参数
if os.environ.get("DINGTALK_SERVER_PORT") is not None and os.environ.get("DINGTALK_SERVER_PORT") != '':
    config = {
        "dingtalk_server_port": os.environ.get("DINGTALK_SERVER_PORT")
    }
    dingtalk_run_mode = os.environ.get("DINGTALK_RUN_MODE")
    if dingtalk_run_mode is not None and dingtalk_run_mode != "":
        config["dingtalk_run_mode"] = dingtalk_run_mode
    else:
        config["dingtalk_run_mode"] = "prod"
else:
    filename = os.path.join(script_dir, 'works/LuckDingtalkConfig.json')
    with open(filename, "r", encoding="utf-8") as fp:
        json_str = fp.read().strip()
        if json_str is None or len(json_str) <= 0:
            pass
        else:
            config = json.loads(json_str)


# 基本认证鉴权
app.config['BASIC_AUTH_USERNAME'] = config["basic_auth_username"]
app.config['BASIC_AUTH_PASSWORD'] = config["basic_auth_password"]
app.config['BASIC_AUTH_FORCE'] = False  # 为True 就默认对所有 api 进行认证， 如果设置为 False， 那么可以通过 @basic_auth.required 对指定 api 进行认证。
basic_auth = BasicAuth(app)


# 检查服务状态
@app.route('/')
@basic_auth.required
def index():
    logging.info(f'小程序 于 {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))} 查看MQ服务部署状态')

    return {
        "code": 1,
        "data": ["/", "/sendLinkMsgToGroup", "/sendTextToGroup", "/sendFeedcardMsgToGroup", "/sendActioncardMsgToPerson", "/sendLinkMsgToPerson", "/sendTextMsgToPerson", "/createTable", "/deleteTable", "/dropTable"],
        "msg": "钉钉服务部署成功"
    }


# 删除记录表数据
@app.route('/createTable')
@basic_auth.required
def create_table():
    logging.info(f'小程序 于 {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))} 创建表')

    server_service = LuckDingtalkService(config)
    return server_service.create_table()


# 删除记录表数据
@app.route('/deleteTable')
@basic_auth.required
def delete_table():
    logging.info(f'小程序 于 {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))} 删除表数据')

    server_service = LuckDingtalkService(config)
    return server_service.delete_table()


# 删除记录表
@app.route('/dropTable')
@basic_auth.required
def drop_table():
    logging.info(f'小程序 于 {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))} 删除表')

    server_service = LuckDingtalkService(config)
    return server_service.drop_table()


# 通过钉钉群机器人发送群feedCard消息
@app.route('/sendFeedcardMsgToGroup', methods=['POST'])
@basic_auth.required
def send_feedcard_msg_to_group():
    if "debug" == config["dingtalk_run_mode"].lower():
        data = {
            "dingtalk_robot_list": [
                {
                    "dingtalk_robot_secret": "SEC108c2176b230090e8bede00717d04e8455aabb0fe5a747eddb42b17a1d385416",
                    "dingtalk_robot_access_token": "7144ea46a2a09b877935eda8171c1e872e7ee0990fbf45b2e18d9927a3442ade"
                }
            ],
            "dingtalk_content_list": [
                {
                    "title": "这是Feedcard标题1",
                    "messageURL": "https://www.baidu.com",
                    "picURL": "http://www.ahyungui.com/Public/Upload/column/18/2021-01-06/7188548b-0984-4c6c-8fb3-ce0d8ff6a148.png"
                },
                {
                    "title": "这是Feedcard标题2",
                    "messageURL": "https://www.baidu.com",
                    "picURL": "http://www.ahyungui.com/Public/Upload/column/18/2021-01-06/7188548b-0984-4c6c-8fb3-ce0d8ff6a148.png"
                }
            ]
        }
        custom_config = {
            "dingtalk_robot_list": data["dingtalk_robot_list"]
        }
        dingtalk_content_list = data["dingtalk_content_list"]
        service = LuckDingtalkService(custom_config)
        return service.send_feedcard_msg_to_group(dingtalk_content_list)
    else:
        data = json.loads(request.data)
        custom_config = {
            "dingtalk_robot_list": data["dingtalk_robot_list"]  # 钉钉机器人密钥和token信息集合（必须传递）
        }
        dingtalk_content_list = data["dingtalk_content_list"]  # feedCard链接信息集合（必须传递）
        service = LuckDingtalkService(custom_config)
        return service.send_feedcard_msg_to_group(dingtalk_content_list)


# 通过钉钉群机器人发送群链接消息
@app.route('/sendLinkMsgToGroup', methods=['POST'])
@basic_auth.required
def send_link_msg_to_group():
    if "debug" == config["dingtalk_run_mode"].lower():
        data = {
            "dingtalk_robot_list": [
                {
                    "dingtalk_robot_secret": "SEC108c2176b230090e8bede00717d04e8455aabb0fe5a747eddb42b17a1d385416",
                    "dingtalk_robot_access_token": "7144ea46a2a09b877935eda8171c1e872e7ee0990fbf45b2e18d9927a3442ade"
                }
            ],
            "dingtalk_content": {
                "text": "这里是Link内容",
                "title": "这里是Link标题",
                "picUrl": "http://www.ahyungui.com/Public/Upload/column/18/2021-01-06/7188548b-0984-4c6c-8fb3-ce0d8ff6a148.png",
                "messageUrl": "https://www.taobao.com"
            }
        }
        custom_config = {
            "dingtalk_robot_list": data["dingtalk_robot_list"]
        }
        dingtalk_content = data["dingtalk_content"]
        service = LuckDingtalkService(custom_config)
        return service.send_link_msg_to_group(dingtalk_content)
    else:
        data = json.loads(request.data)
        custom_config = {
            "dingtalk_robot_list": data["dingtalk_robot_list"]  # 钉钉机器人密钥和token信息集合（必须传递）
        }
        dingtalk_content = data["dingtalk_content"]  # 链接信息（必须传递）
        service = LuckDingtalkService(custom_config)
        return service.send_link_msg_to_group(dingtalk_content)


# 通过钉钉群机器人发送群文本消息
@app.route('/sendTextToGroup', methods=['POST'])
@basic_auth.required
def send_text_msg_to_group():
    if "debug" == config["dingtalk_run_mode"].lower():
        data = {
            "dingtalk_robot_list": [
                {
                    "dingtalk_robot_secret": "SEC108c2176b230090e8bede00717d04e8455aabb0fe5a747eddb42b17a1d385416",
                    "dingtalk_robot_access_token": "7144ea46a2a09b877935eda8171c1e872e7ee0990fbf45b2e18d9927a3442ade"
                }
            ],
            "dingtalk_content": {
                "content": "这里是Text内容"
            }
        }
        custom_config = {
            "dingtalk_robot_list": data["dingtalk_robot_list"]  # 钉钉机器人密钥和token信息集合（必须传递）
        }
        dingtalk_content = data["dingtalk_content"]  # 文本信息（必须传递）
        service = LuckDingtalkService(custom_config)
        return service.send_text_msg_to_group(dingtalk_content)
    else:
        data = json.loads(request.data)
        custom_config = {
            "dingtalk_robot_list": data["dingtalk_robot_list"]  # 钉钉机器人密钥和token信息集合（必须传递）
        }
        dingtalk_content = data["dingtalk_content"]  # 文本信息（必须传递）
        service = LuckDingtalkService(custom_config)
        return service.send_text_msg_to_group(dingtalk_content)


# 发送个人钉钉ActionCard消息
@app.route('/sendActioncardMsgToPerson', methods=['POST'])
@basic_auth.required
def send_actioncard_msg_to_person():
    if "debug" == config["dingtalk_run_mode"].lower():
        data = {
            "dingtalk_agent_id": 804578772,
            "dingtalk_app_key": "dingkwmfrbsv0cencgb9",
            "dingtalk_app_secret": "_OVByoifueYAH0X6mAQjleWfgFhB0cfZ3v4MNgAHrfjYG-a_u4ULXbN9ujdpoVOe",
            "dingtalk_userid_list": [
                "023405250820658815"
            ],
            "dingtalk_content": {
                "title": f"这是Actioncard标题{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))}",
                "markdown": "这是Actioncard内容",
                "single_title": "查看详情",
                "single_url": "https://www.baidu.com",
                "btn_orientation": "1",
                "btn_json_list": [
                    {
                        "title": "查看",
                        "action_url": "https://www.taobao.com"
                    }
                ]
            }
        }
        custom_config = {
            "dingtalk_agent_id": data["dingtalk_agent_id"],  # 钉钉机器人Agentid（必须传递）
            "dingtalk_app_key": data["dingtalk_app_key"],  # 钉钉机器人Appkey（必须传递）
            "dingtalk_app_secret": data["dingtalk_app_secret"] # 钉钉机器人Appsecret（必须传递）
        }
        dingtalk_userid_list = data["dingtalk_userid_list"]  # 钉钉用户id集合（必须传递）
        dingtalk_content = data["dingtalk_content"]  # 钉钉Actioncard消息（必须传递）
        service = LuckDingtalkService(custom_config)
        return service.send_actioncard_msg_to_person(dingtalk_content, dingtalk_userid_list)
    else:
        data = json.loads(request.data)
        custom_config = {
            "dingtalk_agent_id": data["dingtalk_agent_id"],  # 钉钉机器人Agentid（必须传递）
            "dingtalk_app_key": data["dingtalk_app_key"],  # 钉钉机器人Appkey（必须传递）
            "dingtalk_app_secret": data["dingtalk_app_secret"]  # 钉钉机器人Appsecret（必须传递）
        }
        dingtalk_userid_list = data["dingtalk_userid_list"]  # 钉钉用户id集合（必须传递）
        dingtalk_content = data["dingtalk_content"]  # 钉钉Actioncard消息（必须传递）
        service = LuckDingtalkService(custom_config)
        return service.send_actioncard_msg_to_person(dingtalk_content, dingtalk_userid_list)


# 发送个人钉钉链接消息
@app.route('/sendLinkMsgToPerson', methods=['POST'])
@basic_auth.required
def send_link_msg_to_person():
    if "debug" == config["dingtalk_run_mode"].lower():
        data = {
            "dingtalk_agent_id": 804578772,
            "dingtalk_app_key": "dingkwmfrbsv0cencgb9",
            "dingtalk_app_secret": "_OVByoifueYAH0X6mAQjleWfgFhB0cfZ3v4MNgAHrfjYG-a_u4ULXbN9ujdpoVOe",
            "dingtalk_userid_list": [
                "023405250820658815"
            ],
            "dingtalk_content": {
                "text": f'这里Link内容{time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))}',
                "title": "这里Link标题",
                "picUrl": "http://www.ahyungui.com/Public/Upload/column/18/2021-01-06/7188548b-0984-4c6c-8fb3-ce0d8ff6a148.png",
                "messageUrl": "https://www.taobao.com"
            }
        }
        custom_config = {
            "dingtalk_agent_id": data["dingtalk_agent_id"],  # 钉钉机器人Agentid（必须传递）
            "dingtalk_app_key": data["dingtalk_app_key"],  # 钉钉机器人Appkey（必须传递）
            "dingtalk_app_secret": data["dingtalk_app_secret"]  # 钉钉机器人Appsecret（必须传递）
        }
        dingtalk_userid_list = data["dingtalk_userid_list"]  # 钉钉用户id集合（必须传递）
        dingtalk_content = data["dingtalk_content"]  # 钉钉链接消息（必须传递）
        service = LuckDingtalkService(custom_config)
        return service.send_link_msg_to_person(dingtalk_content, dingtalk_userid_list)
    else:
        data = json.loads(request.data)
        custom_config = {
            "dingtalk_agent_id": data["dingtalk_agent_id"],  # 钉钉机器人Agentid（必须传递）
            "dingtalk_app_key": data["dingtalk_app_key"],  # 钉钉机器人Appkey（必须传递）
            "dingtalk_app_secret": data["dingtalk_app_secret"]  # 钉钉机器人Appsecret（必须传递）
        }
        dingtalk_userid_list = data["dingtalk_userid_list"]  # 钉钉用户id集合（必须传递）
        dingtalk_content = data["dingtalk_content"]  # 钉钉链接消息（必须传递）
        service = LuckDingtalkService(custom_config)
        return service.send_link_msg_to_person(dingtalk_content, dingtalk_userid_list)


# 发送个人钉钉文本消息
@app.route('/sendTextMsgToPerson', methods=['POST'])
@basic_auth.required
def send_text_msg_to_person():
    if "debug" == config["dingtalk_run_mode"].lower():
        data = {
            "dingtalk_agent_id": 804578772,
            "dingtalk_app_key": "dingkwmfrbsv0cencgb9",
            "dingtalk_app_secret": "_OVByoifueYAH0X6mAQjleWfgFhB0cfZ3v4MNgAHrfjYG-a_u4ULXbN9ujdpoVOe",
            "dingtalk_userid_list": [
                "023405250820658815"
            ],
            "dingtalk_content": f"这里Text内容{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))}"
        }
        custom_config = {
            "dingtalk_agent_id": data["dingtalk_agent_id"],  # 钉钉机器人Agentid（必须传递）
            "dingtalk_app_key": data["dingtalk_app_key"],  # 钉钉机器人Appkey（必须传递）
            "dingtalk_app_secret": data["dingtalk_app_secret"]  # 钉钉机器人Appsecret（必须传递）
        }
        dingtalk_userid_list = data["dingtalk_userid_list"]  # 钉钉用户id集合（必须传递）
        dingtalk_content = {
            "content": data["dingtalk_content"]  # 钉钉文本消息（必须传递）
        }
        service = LuckDingtalkService(custom_config)
        return service.send_text_msg_to_person(dingtalk_content, dingtalk_userid_list)
    else:
        data = json.loads(request.data)
        custom_config = {
            "dingtalk_agent_id": data["dingtalk_agent_id"],  # 钉钉机器人Agentid（必须传递）
            "dingtalk_app_key": data["dingtalk_app_key"],  # 钉钉机器人Appkey（必须传递）
            "dingtalk_app_secret": data["dingtalk_app_secret"]  # 钉钉机器人Appsecret（必须传递）
        }
        dingtalk_userid_list = data["dingtalk_userid_list"]  # 钉钉用户id集合（必须传递）
        dingtalk_content = {
            "content": data["dingtalk_content"]  # 钉钉文本消息（必须传递）
        }
        service = LuckDingtalkService(custom_config)
        return service.send_text_msg_to_person(dingtalk_content, dingtalk_userid_list)

if __name__ == '__main__':
    # 先删除记录表，再创建记录表
    custom_config = {

    }
    service = LuckDingtalkService(custom_config)
    service.drop_table()
    service.create_table()

    # use_reloader=False禁用重新加载器
    # 以命令行方式启动manager.run()
    app.run(debug=False, use_reloader=False, host='0.0.0.0', port=config["dingtalk_server_port"])
